/*
 * Copyright 2014-2016 CyberVision, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.kaaproject.kaa.server.datamigration.utils.datadefinition;

import static java.lang.String.format;

import org.apache.commons.dbutils.QueryRunner;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class DataDefinition {
  private static final String QUERY_FIND_FK_NAME = "SELECT CONSTRAINT_NAME FROM "
      + "INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE REFERENCED_TABLE_SCHEMA = 'kaa'"
      + " AND TABLE_NAME = '%s' and referenced_table_name='%s'";

  private Connection connection;

  public DataDefinition(Connection connection) {
    this.connection = connection;
  }

  public AlterBuilder alterTable(String tableName) {
    return new AlterBuilder(tableName);
  }

  /**
   * Drop foreign key with autogenerated name based on the table where constrain declared and
   * referenced table name.
   */
  public void dropUnnamedFk(String tableName, String referencedTableName) throws SQLException {
    QueryRunner runner = new QueryRunner();
    String query = String.format(QUERY_FIND_FK_NAME, tableName, referencedTableName);
    String fkName = runner.query(connection, query, rs -> rs.next() ? rs.getString(1) : null);
    if (fkName != null) {
      runner.update(connection, "ALTER TABLE " + tableName + " DROP FOREIGN KEY " + fkName);
    } else {
      System.err.println("FK name not found");
    }
  }

  public class AlterBuilder {
    private String tableName;
    private List<Constraint> addConstrains = new ArrayList<>();

    AlterBuilder(String tableName) {
      this.tableName = tableName;
    }

    public AlterBuilder add(Constraint constraint) {
      addConstrains.add(constraint);
      return this;
    }

    /**
     * Execute created query.
     *
     * @throws SQLException the sql exception
     */
    public void execute() throws SQLException {
      StringBuilder sql = new StringBuilder("ALTER TABLE " + tableName + "\n");
      for (int i = 0; i < addConstrains.size(); i++) {
        Constraint constraint = addConstrains.get(i);
        switch (constraint.getType()) {
          case FK:
            sql.append(format("ADD CONSTRAINT %s FOREIGN KEY (%s) REFERENCES %s(%s) \n",
                constraint.getConstraintName(),
                constraint.getField(),
                constraint.getReferencedTable(),
                constraint.getReferencedField())
            );

            if (constraint.getOnDeleteOpt() != null) {
              sql.append("ON DELETE " + constraint.getOnDeleteOpt() + "\n");
            }

            if (constraint.getOnUpdateOpt() != null) {
              sql.append("ON UPDATE " + constraint.getOnUpdateOpt() + "\n");
            }
            break;
          case PK:
            sql.append(format("ADD CONSTRAINT %s PRIMARY KEY (%s)\n",
                constraint.getConstraintName(), constraint.getField()));
            break;
          case UNIQUE:
            sql.append(format("ADD CONSTRAINT %s UNIQUE (%s)\n",
                constraint.getConstraintName(), constraint.getField()));
            break;
          default:
            break;
        }

        if (i < addConstrains.size() - 1) {
          sql.append(", \n");
        } else {
          sql.append(";");
        }
      }

      QueryRunner runner = new QueryRunner();
      runner.update(connection, sql.toString());
    }
  }

}
